class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int n = matrix.size();
        int m = matrix[0].size();
        int left = 0;
        int right = n * m - 1;
        while (left <= right) {
            int mid = ((right - left) / 2) + left;
            int x = matrix[mid / m][mid % m];
            if (x == target) {
                return true;
            } else if (x < target) {
                left = mid + 1;
            } else if (x > target) {
                right = mid - 1;
            }
        }
        return false;
    }
};